import React ,{useState,useEffect,useLayoutEffect} from 'react';
import { Input,InputNumber,Cascader,Upload,Checkbox,Button,message,Tooltip } from 'antd';
import ImgCrop from 'antd-img-crop';
import './management.css';
import {useHistory} from 'react-router-dom'
// import Axios from "../../util/axios";
// import goods_management from "../../api/goods_management";
import axios from 'axios'
// import api from "../../api"
import Uploadpic from './Uploadpic'
import management from '../../store/management'


function Publish () {

    // 上传图片1
    const [fileList, setFileList] = useState([]);
    const onChange = ({fileList: newFileList}) => {
        setFileList(newFileList);
    };
    const onPreview = async file => {
        let src = file.url;
        if (!src) {
            src = await new Promise(resolve => {
                const reader = new FileReader();
                reader.readAsDataURL(file.originFileObj);
                reader.onload = () => resolve(reader.result);
            });
        }
    const image = new Image();
    image.src = src;
    const imgWindow = window.open(src);
    imgWindow.document.write(image.outerHTML);
    };
    const beforeUploadMains = () => { // 自定义上传事件
        return false; // 《《= 关键 阻止upload默认上传事件
    }
    // 上传图片2
    // const [fileList1, setFileList1] = useState([]);
    // const onChange1 = ({fileList1: newFileList1}) => {
    //     setFileList1(newFileList1);
    //
    // };
    // const onPreview1 = async file => {
    //     let src = file.url;
    //     if (!src) {
    //         src = await new Promise(resolve => {
    //             const reader = new FileReader();
    //             reader.readAsDataURL(file.originFileObj);
    //             reader.onload = () => resolve(reader.result);
    //         });
    //     }
    //     const image1 = new Image();
    //     image1.src = src;
    //     const imgWindow1 = window.open(src);
    //     imgWindow1.document.write(image1.outerHTML);
    // };
    // const fileList1 = [];

    // 二级联动
    const [options,setOptions ]= useState(
        [
            {
                value: '奢侈品',
                label: '奢侈品',
                children: [
                    {
                        value: 'hangzhou',
                        label: 'Hangzhou',
                    }
                ]
            },
            {
                value: 'jiangsu',
                label: 'Jiangsu',
                children: [
                    {
                        value: 'nanjing',
                        label: 'Nanjing',
                    }
                ]
            },
        ]
    )




// 得到输入的值
    // 1、商品名字
    const [shopNameValue,setShopNameValue] = useState()
    const shopName = (e) =>{
        // setShopNameValue(e.target.value)
        //     console.log("名称",shopNameValue)

        setShopNameValue(() => {
            return e.target.value
        })
        // // console.log("名称",shopNameValue)
    }
    // 2、图片数组fileList
    // 3、商品类别二级联动
    const [typeValue,setTypeValue] = useState()
    const onChange2= (value) => {
        setTypeValue(value)
        console.log("typeValue",typeValue);
    }
        //根据groupId去搜索商品类别名

    // const [file,setFile] = useState(management.data)


    // 4、数字输入框--库存
    const [numValue,setNumValue] = useState()
    const [numValue1,setNumValue1] = useState()
    const [numValue2,setNumValue2] = useState()
    const onChangeNum = (value) => {
        setNumValue(value)
        console.log('changed', numValue);
    }
    const onChangeNum1 = (value) => {
        setNumValue1(value)
        console.log('changed1', numValue1);
    }
    const onChangeNum2 = (value) => {
        setNumValue2(value)
        console.log('changed2', numValue2);
    }
    // 5、规格设置
    const [sizeValue,setSizeValue] = useState()
    const [colorValue,setColorValue] = useState()
    const [brandValue,setBrandValue] = useState()
    const [placeValue,setPlaceValue] = useState()
    const size = (e) => {
        setSizeValue(e.target.value)
        console.log('changed11', sizeValue);
    }
    const color = (e) => {
        setColorValue(e.target.value)
        console.log('changed22', colorValue);
    }
    const brand = (e) => {
        setBrandValue(e.target.value)
        console.log('changed33', brandValue);
    }
    const place = (e) => {
        setPlaceValue(e.target.value)
        console.log('changed44', placeValue);
    }
    // 6、图片数组fileList1
    // 7、多选框(协议)
    const [checked,setChecked] = useState()
    const onChange3 = (e) => {
        setChecked(e.target.checked)
        console.log(`checked = `,checked);
    }





    // console.log(this.refs.tupi.tupi)

    //生命周期，数据改变之后就更新
    useEffect(() => {
            // 二级下拉数据请求
            console.log('fu effect',management.data)
        }
        // ,
        // [
        //     checked,
        //     shopNameValue,
        //     fileList,
        //     typeValue,
        //     numValue,
        //     numValue1,
        //     numValue2,
        //     sizeValue,
        //     colorValue,
        //     brandValue,
        //     placeValue,
        //     fileList1,
        //     options
        // ]
    )

 useLayoutEffect(()=>{
     console.log('useLayoutEffect');
     console.log(management.data);
     const erjixiala = () => {
         // 请求下拉列表的数据
         let yiji = []
         axios.post("/api/backstage/shop/findAllGroups").then((res) => {
             //把拿到的扁平数据转化为属性数据
             let data = res.data.data
             for (let i = 0; i < data.length; i++) {
                 if (data[i].groupLevel === 1) {
                     yiji.push(data[i])
                 }
             }
             for (let i = 0; i < yiji.length; i++) {
                 if (!yiji[i].children) {
                     yiji[i].children = []
                 }
                 for (let j = 0; j < data.length; j++) {
                     if (data[j].groupLevel === 2 && data[j].groupParentId === yiji[i].groupId) {
                         yiji[i].children.push(data[j])
                     }
                 }
             }
             // console.log(yiji)
             yiji = getList(yiji,'value','groupId')
             yiji = getList(yiji,'label','groupName')
             console.log(yiji)
             setOptions(yiji)
         })
     }
     //把获取到二级下拉数据转换成option相同的属性value和label
     const getList=(list,newKey,oldKey)=>{
         list.forEach(item=>{
             if(item.children && item.children.length>0){
                 item[newKey] = item[oldKey];
                 delete item[oldKey];
                 getList(item.children,newKey,oldKey)
             }else {
                 item[newKey] = item[oldKey];
                 delete item[oldKey]
             }
         });
         return list;
     }
     erjixiala()
 },[])

    // 点击发布
    let history = useHistory()
    const publish = () => {
        if (checked === true){
            //&& fileList1.length === 5
            if(fileList.length === 6 ){
                if (shopNameValue!=='' &&
                    typeValue!=='' &&
                    numValue!=='' &&
                    numValue1!=='' &&
                    numValue2!=='' &&
                    sizeValue!=='' &&
                    colorValue!=='' &&
                    brandValue!=='' &&
                    placeValue!==''){

                    let formData=new FormData();
                    // console.log(fileList)
                    formData.append('goodsName',shopNameValue);
                    formData.append('picimgFile1',fileList[0].originFileObj);
                    formData.append('picimgFile2',fileList[1].originFileObj);
                    formData.append('picimgFile3',fileList[2].originFileObj);
                    formData.append('picimgFile4',fileList[3].originFileObj);
                    formData.append('picimgFile5',fileList[4].originFileObj);
                    formData.append('picimgFile6',fileList[5].originFileObj);
                    formData.append('goodsGroupId',typeValue);
                    formData.append('goodsRealPrice',numValue);
                    formData.append('goodsHighPrice',numValue1);
                    formData.append('goodsNumber',numValue2);
                    // formData.append('goodsSize',fileList1);
                    formData.append('goodsColor',sizeValue);
                    formData.append('goodsBrand',colorValue);
                    formData.append('goodsPlace',brandValue);
                    formData.append('userName',placeValue);
                    // formData.append('descimgFile7',fileList1[0].originFileObj);
                    // formData.append('descimgFile8',fileList1[1].originFileObj);
                    // formData.append('descimgFile9',fileList1[2].originFileObj);
                    // formData.append('descimgFile10',fileList1[3].originFileObj);
                    // formData.append('descimgFile11',fileList1[4].originFileObj);

                    // console.log("名字",shopNameValue)
                    // console.log("formData",formData)

                    history.push('/selling')
                    axios({
                        method:'post',
                        url:'/api/backstage/shop/uploadGoods',
                        header: {'Content-Type':'multipart/form-data'},
                        data:formData
                    }).then(res=>{
                        console.log(res)
                    })
                    // axios.post('/api/backstage/shop/uploadGoods',{
                    //     formData
                    // })

                }
            }else {
                message.warning('请上传相应数量的图片');
            }

        }else {
            message.warning('请勾选协议');
        }

    }

    return (
        <div className="div_content">

            {/*基本信息*/}
            <div className="div_kuai">
                <div className="title">基本信息</div>
                <div className="jutiContent">
                    <div  className='div_inp'>
                        <span className="mingcheng"><span className="red_xing">*</span>商品名称：</span>
                        <Input placeholder="输入商品名称" onChange={shopName}/>
                    </div>
                    <div>
                        <span><span className="red_xing">*</span>商品图片(请上传6张图片)：</span>

                            <ImgCrop rotate>
                                <Tooltip placement="topLeft" title='请上传6张图片'>
                                <Upload
                                    // action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
                                    listType="picture-card"
                                    fileList={fileList}
                                    onChange={onChange}
                                    onPreview={onPreview}
                                    beforeUpload={beforeUploadMains}
                                >
                                    {fileList.length < 6 && '+ 点击上传'}
                                </Upload>
                                </Tooltip>
                            </ImgCrop>

                    </div>
                    <div>
                        <span><span className="red_xing">*</span>商品类别：</span>
                        <Cascader options={options} onChange={onChange2} placeholder="请选择" />
                    </div>
                </div>
            </div>

            {/*价格设置*/}
            <div  className="div_kuai">
                <div className="title">价格设置</div>
                <div className="jutiContent">
                    <div className='div_inp'>
                        <span><span className="red_xing">*</span>售价：</span>
                        <InputNumber className='inp' min={1} max={10} defaultValue={3} onChange={onChangeNum} />
                    </div>
                    <div className='div_inp'>
                        <span><span className="red_xing">*</span>市场价：</span>
                        <InputNumber min={1} max={10} defaultValue={3} onChange={onChangeNum1} />
                    </div>
                    <div className='div_inp'>
                        <span><span className="red_xing">*</span>库存：</span>
                        <InputNumber className='inp' min={1} max={10} defaultValue={3} onChange={onChangeNum2} />
                    </div>
                </div>
            </div>

            {/*规格设置*/}
            <div  className="div_kuai">
                <div className="title">规格设置</div>
                <div className='div_inp jutiContent'>
                    <div className="guige"><span><span className="red_xing">*</span>尺寸：</span><Input placeholder="输入尺寸" onChange={size}/></div>
                    <div className="guige"><span><span className="red_xing">*</span>颜色：</span><Input placeholder="输入颜色" onChange={color}/></div>
                    <div className="guige"><span><span className="red_xing">*</span>品牌：</span><Input placeholder="输入品牌" onChange={brand}/></div>
                    <div className="guige"><span><span className="red_xing">*</span>产地：</span><Input placeholder="输入产地" onChange={place}/></div>
                </div>
            </div>

            {/*商品详情*/}
            <div  className="div_kuai">
                <div className="title">商品详情</div>
                <div className="jutiContent">
                    <div className="kuozhan">支持扩展名：.jpg .jpeg .gif .png，图片大小不超过5M，共上传5张图片</div>
                    <div>
                                <Uploadpic/>

                    </div>
                </div>
            </div>

            {/*底部按钮*/}
            <div className="publish_footer">
                <Checkbox onChange={onChange3}>我已阅读并同意商品发布规范</Checkbox>
                <Button type="primary" className="fabu" onClick={publish}>发布</Button>
            </div>

        </div>
    )
}

export default Publish